<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="success" size="small" plain v-if="permissionList" icon="el-icon-upload2" @click="handleImport">导 入</el-button>
        <el-button type="warning" size="small" plain v-if="permissionList" icon="el-icon-upload1" @click="handleExport">导 出</el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.sjofflinetrainingrecord_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <!-- 附件表单自定义 -->
      <template slot="cjpxFjForm">
        <div>
          <el-upload action="/api/fileManager/upload/file" :headers="SetHeaders" :file-list="cjpxFjFileList" :before-upload="beforeUploadCjpxFj" :on-remove="handleRemoveCjpxFj" :on-success="uploadCjpxFjSuccess">
            <el-button size="small" type="primary">选择文件</el-button>
          </el-upload>
        </div>
      </template>
      <template slot="chepxFjForm">
        <div>
          <el-upload action="/api/fileManager/upload/file" :headers="SetHeaders" :file-list="chepxFjFileList" :before-upload="beforeUploadChepxFj" :on-remove="handleRemoveChepxFj" :on-success="uploadChepxFjSuccess">
            <el-button size="small" type="primary">选择文件</el-button>
          </el-upload>
        </div>
      </template>
      <template slot="bzFjForm">
        <div>
          <el-upload action="/api/fileManager/upload/file" :headers="SetHeaders" :file-list="bzFjFileList" :before-upload="beforeUploadBzFj" :on-remove="handleRemoveBzFj" :on-success="uploadBzFjSuccess">
            <el-button size="small" type="primary">选择文件</el-button>
          </el-upload>
        </div>
      </template>
    </avue-crud>

    <el-dialog title="数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :show-file-list="false" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/jypx/edusjofflinetrainingrecord/sjofflinetrainingrecord";
  import {mapGetters} from "vuex";
  import {getToken} from "../../../util/auth";
  import {validateIsPositive} from "../../../api/mmhi/validate";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "姓名",
              prop: "xm",
              search: true,
              align: "center",
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }]
            },
            {
              label: "培训分类",
              prop: "pxfl",
              align: "center",
              type:"select",
              dataType: "number",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=sjOfflineTrainingRecord_pxfl",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入培训分类",
                trigger: "blur"
              }]
            },
            {
              label: "厂级教育人",
              prop: "cjpxJyr",
              width:"90px",
              align: "center",
              rules: [{
                required: true,
                message: "请输入厂级教育人",
                trigger: "blur"
              }]
            },
            {
              label: "课程名称",
              prop: "cjpxKcmc",
              align: "center",
              rules: [{
                required: true,
                message: "请输入课程名称",
                trigger: "blur"
              }]
            },
            {
              label: "厂级培训开始时间",
              prop: "cjpxStartTime",
              width:"140px",
              align: "center",
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              rules: [{
                required: true,
                message: "请输入厂级培训开始时间",
                trigger: "blur"
              }]
            },
            {
              label: "厂级培训结束时间",
              prop: "cjpxEndTime",
              width:"140px",
              align: "center",
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              rules: [{
                required: true,
                message: "请输入厂级培训结束时间",
                trigger: "blur"
              }]
            },
            {
              label: "厂级培训内容",
              prop: "cjpxNr",
              width:"150px",
              span: 24,
              align: "center",
              rules: [{
                required: true,
                message: "请输入厂级培训内容",
                trigger: "blur"
              }]
            },
            {
              label: "厂级考试成绩",
              prop: "cjpxCj",
              width:"100px",
              align: "center",
              rules: [{
                required: true,
                validator:validateIsPositive,
                trigger: "blur"
              }]
            },
            {
              label: "厂级是否合格",
              prop: "cjpxSfhg",
              width:"100px",
              align: "center",
              type:"select",
              dataType: "number",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=rcofflinetrainrecord_pxjg",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入厂级是否合格",
                trigger: "blur"
              }]
            },
            {
              label: "厂级附件",
              prop: "cjpxFj",
              align: "center",
              span: 24,
              slot: true,
              formslot: true,
              hide:true,
              viewDisplay:false,
              rules: [{
                required: true,
                message: "请输入厂级附件",
                trigger: "blur"
              }]
            },
            {
              label: "车间教育人",
              prop: "chepxJyr",
              width:"90px",
              align: "center",
              rules: [{
                required: true,
                message: "请输入车间教育人",
                trigger: "blur"
              }]
            },
            {
              label: "车间课程名称",
              prop: "chepxKcmc",
              align: "center",
              width:"100px",
              rules: [{
                required: true,
                message: "请输入车间课程名称",
                trigger: "blur"
              }]
            },
            {
              label: "车间培训时间开始",
              prop: "chepxStartTime",
              align: "center",
              width:"140px",
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              rules: [{
                required: true,
                message: "请输入车间培训时间开始",
                trigger: "blur"
              }]
            },
            {
              label: "车间培训教育结束",
              prop: "chepxEndTime",
              align: "center",
              width:"140px",
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              rules: [{
                required: true,
                message: "请输入车间培训教育结束",
                trigger: "blur"
              }]
            },
            {
              label: "车间培训内容",
              prop: "chepxNr",
              width:"120px",
              span: 24,
              align: "center",
              rules: [{
                required: true,
                message: "请输入车间培训内容",
                trigger: "blur"
              }]
            },
            {
              label: "车间考试成绩",
              prop: "chepxCj",
              width:"100px",
              align: "center",
              rules: [{
                required: true,
                validator:validateIsPositive,
                trigger: "blur"
              }]
            },
            {
              label: "车间是否合格",
              prop: "chepxSfhg",
              width:"100px",
              align: "center",
              type:"select",
              dataType: "number",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=rcofflinetrainrecord_pxjg",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入车间是否合格",
                trigger: "blur"
              }]
            },
            {
              label: "车间附件",
              prop: "chepxFj",
              align: "center",
              slot: true,
              formslot: true,
              viewDisplay:false,
              hide:true,
              span: 24,
              rules: [{
                required: true,
                message: "请输入车间附件",
                trigger: "blur"
              }]
            },
            {
              label: "班组教育人",
              prop: "bzJyr",
              width:"100px",
              align: "center",
              rules: [{
                required: true,
                message: "请输入班组教育人",
                trigger: "blur"
              }]
            },
            {
              label: "班组课程名称",
              prop: "bzKcmc",
              width:"100px",
              align: "center",
              rules: [{
                required: true,
                message: "请输入班组课程名称",
                trigger: "blur"
              }]
            },
            {
              label: "班组培训时间开始",
              prop: "bzStartTime",
              align: "center",
              width:"150px",
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              rules: [{
                required: true,
                message: "请输入班组培训时间开始",
                trigger: "blur"
              }]
            },
            {
              label: "班组培训教育结束",
              prop: "bzEndTime",
              align: "center",
              width:"150px",
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              rules: [{
                required: true,
                message: "请输入班组培训教育结束",
                trigger: "blur"
              }]
            },
            {
              label: "班组培训内容",
              prop: "bzNr",
              span: 24,
              width:"140px",
              align: "center",
              rules: [{
                required: true,
                message: "请输入班组培训内容",
                trigger: "blur"
              }]
            },
            {
              label: "班组考试成绩",
              prop: "bzCj",
              width:"100px",
              align: "center",
              rules: [{
                required: true,
                validator:validateIsPositive,
                trigger: "blur"
              }]
            },
            {
              label: "班组是否合格",
              prop: "bzSfhg",
              width:"100px",
              align: "center",
              type:"select",
              dataType: "number",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=rcofflinetrainrecord_pxjg",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入班组是否合格",
                trigger: "blur"
              }]
            },
            {
              label: "班组附件",
              prop: "bzFj",
              align: "center",
              span: 24,
              slot: true,
              formslot: true,
              viewDisplay:false,
              hide:true,
              rules: [{
                required: true,
                message: "请输入班组附件",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              row:true,
              hide: true,
              type: "textarea",
              maxlength:500,
              span: 24,
              minrows:6,

            }
          ]
        },
        data: [],
        // 厂级附件
        cjpxFjFileList: [],
        //车间附件
        chepxFjFileList: [],
        //班组附件
        bzFjFileList: [],
        downloadHead: "/api/fileManager/download/",
        SetHeaders: { "Blade-Auth": getToken() },
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [{
            label: '表格导入',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '表格导入中，请稍等',
            showFileList: false,
            span: 24,
            propsHttp: {
              fileName: 'file',
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/eduSjOfflineTrainingRecord/sjofflinetrainingrecord/import-sjOfflineTrainingRecord",
            headers: {}
          },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.sjofflinetrainingrecord_add, false),
          viewBtn: this.vaildData(this.permission.sjofflinetrainingrecord_view, false),
          delBtn: this.vaildData(this.permission.sjofflinetrainingrecord_delete, false),
          editBtn: this.vaildData(this.permission.sjofflinetrainingrecord_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleTemplate() {
        window.open(`/api/eduSjOfflineTrainingRecord/sjofflinetrainingrecord/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      handleExport() {
        this.$confirm("是否导出三级线下培训记录?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/eduSjOfflineTrainingRecord/sjofflinetrainingrecord/export-sjOfflineTrainingRecord?${this.website.tokenHeader}=${getToken()}`);
        });
      },

      // 弹出导入框
      handleImport() {
        this.excelBox = true;
      },

      // 导入前判断
      beforeUpload(file, done, loading) {
        this.isFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
          loading()
        } else {
          done()
        }
      },

      // 导入失败后
      uploadError(error, column) {
        console.log(error,column);
        this.isFailed = true;
      },

      // 导入成功后
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.excelBox = false;
        this.refreshChange();
        done();
      },

      // 取消
      cancle() {
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },

      // 上传厂级附件前
      beforeUploadCjpxFj() {
        const isLimit = this.cjpxFjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传厂级附件成功
      uploadCjpxFjSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.cjpxFjFileList = fileList;
        this.form.cjpxFj = response.data.id;
      },

      // 删除厂级附件
      handleRemoveCjpxFj(file, fileList) {
        this.cjpxFjFileList = fileList;
        this.form.cjpxFj = "";
      },

      // 上传车间附件前
      beforeUploadChepxFj() {
        const isLimit = this.chepxFjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传车间附件成功
      uploadChepxFjSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.chepxFjFileList = fileList;
        this.form.chepxFj = response.data.id;
      },

      // 删除车间附件
      handleRemoveChepxFj(file, fileList) {
        this.chepxFjFileList = fileList;
        this.form.chepxFj = "";
      },

      // 上传班组附件前
      beforeUploadBzFj() {
        const isLimit = this.bzFjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传班组附件成功
      uploadBzFjSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.bzFjFileList = fileList;
        this.form.bzFj = response.data.id;
      },

      // 删除班组附件
      handleRemoveBzFj(file, fileList) {
        this.bzFjFileList = fileList;
        this.form.bzFj = "";
      },

      rowSave(row, done, loading) {
        if (row.cjpxStartTime>row.cjpxEndTime){
          this.$message.warning("厂级培训时间填写错误,结束时间应该大于开始时间");
          loading();
          return
        }
        if (row.chepxStartTime>row.chepxEndTime){
          this.$message.warning("车间培训时间填写错误,结束时间应该大于开始时间");
          loading();
          return
        }
        if (row.bzStartTime>row.bzEndTime){
          this.$message.warning("班组培训时间填写错误,结束时间应该大于开始时间");
          loading();
          return
        }
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if (row.cjpxStartTime>row.cjpxEndTime){
          this.$message.warning("厂级培训时间填写错误,结束时间应该大于开始时间");
          loading();
          return
        }
        if (row.chepxStartTime>row.chepxEndTime){
          this.$message.warning("车间培训时间填写错误,结束时间应该大于开始时间");
          loading();
          return
        }
        if (row.bzStartTime>row.bzEndTime){
          this.$message.warning("班组培训时间填写错误,结束时间应该大于开始时间");
          loading();
          return
        }
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.cjpxFjFileList=[];
        this.chepxFjFileList=[];
        this.bzFjFileList=[];
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            console.log(this.form)
            if (type === "edit") {
              if (JSON.stringify(this.form.bladeFile) != '{}') {
                this.cjpxFjFileList.push({
                  name: this.form.bladeFile.fileName,
                  response: {
                    code: 200,
                    success: true,
                    msg: "操作成功",
                    data: this.form.bladeFile
                  }
                });
              }
              if (JSON.stringify(this.form.bladeFilex) != '{}') {
                this.chepxFjFileList.push({
                  name: this.form.bladeFilex.fileName,
                  response: {
                    code: 200,
                    success: true,
                    msg: "操作成功",
                    data: this.form.bladeFilex
                  }
                });
              }
              if (JSON.stringify(this.form.bladeFiley) != '{}') {
                this.bzFjFileList.push({
                  name: this.form.bladeFiley.fileName,
                  response: {
                    code: 200,
                    success: true,
                    msg: "操作成功",
                    data: this.form.bladeFiley
                  }
                });
              }
            }
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
